/*
 * @Date: 2025-06-13 10:50:10
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-11-07 11:36:15
 * @FilePath: \corpus\src\pages\resourceManagement\list\component\CreateKnowledge\index.tsx
 */
import { OPENENUM, SENSITIVEENUM } from '@/enum';
import { getCorpusFileData } from '@/services/ant-design-pro/resource';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Button, Col, Drawer, Form, Input, message, Popconfirm, Select } from 'antd';
import type React from 'react';
import { useEffect, useRef, useState } from 'react';
import hooks from '../../hooks';

const EditAngent: React.FC = () => {
  const {
    setCreateKnowledgeVisible,

    createKnowledgeVisible,
    formAnalysis,
    newList,
    getNewListContent,
    saveFileByCorpusContent,
    saveFileByCorpusDataContent,
    getCorpusFileTaskBrief,
    corpusData,
  } = hooks.useContainer();
  const title = '生成知识库';
  const actionRef = useRef<ActionType>(null);
  const tableColumns = [
    {
      dataIndex: 'index',
      width: 46,
      valueType: 'indexBorder',
      title: '序号',
    },
    {
      title: '名称',
      ellipsis: true,
      dataIndex: 'fileName',
      width: 126,
      formItemProps: {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      },
      renderFormItem: () => {
        return <Input placeholder="请输入" />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 126,
      hideInSearch: true,
    },
    {
      title: '语料形成方式',
      dataIndex: 'type',
      width: 126,
      valueType: 'select',
      formItemProps: {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      },
      request: async () => [
        {
          label: '月份',
          value: 1,
        },
        {
          label: '周',
          value: 2,
        },
        {
          label: '自定义',
          value: 3,
        },
        {
          label: '不展示',
          value: 4,
        },
      ],
      // renderText: (_, record) => {},
    },
  ];
  const handleSubmit = () => {
    formAnalysis.validateFields().then(async (vals) => {
      const method = saveFileByCorpusDataContent;
      if (getCorpusFileTaskBrief.data.data.fileTotal === 0) {
        message.error(' 语料库中没有任何语料，不能生成知识库');
        return;
      }
      method.run({
        ...vals,
      });
    });
  };

  const [id, setId] = useState('');

  useEffect(() => {
    if (createKnowledgeVisible && corpusData) {
      formAnalysis.setFieldValue('openProperty', corpusData?.openProperty);
      formAnalysis.setFieldValue('sensitiveLevel', corpusData?.sensitiveLevel);
      formAnalysis.setFieldValue('corpusId', corpusData?.id);
      getCorpusFileTaskBrief.run(corpusData?.id);
      setId(corpusData?.id);
      actionRef.current?.reload();
      getNewListContent.run({
        openProperty: corpusData?.openProperty,
        current: 1,
        pageSize: 100,
      });
    } else if (!createKnowledgeVisible) {
      formAnalysis.resetFields();
    }
  }, [createKnowledgeVisible, corpusData]);
  const onClose = () => {
    formAnalysis.resetFields();
    setCreateKnowledgeVisible(false);
  };
  return (
    <Drawer
      title={title}
      width={800}
      placement="right"
      onClose={onClose}
      open={createKnowledgeVisible}
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '0 20.0px' }}>
          <Button
            onClick={() => {
              formAnalysis.resetFields();
              setCreateKnowledgeVisible(false);
            }}
            type="default"
            style={{ marginRight: '10.0px' }}
          >
            取消
          </Button>
          {getCorpusFileTaskBrief?.data?.data?.fileTotal !== 0 &&
          getCorpusFileTaskBrief?.data?.data?.parseUnsuccess !== 0 ? (
            <Popconfirm
              title="确认生成知识库文件?"
              onConfirm={handleSubmit}
              okText="确认"
              cancelText="取消"
            >
              <Button type="primary">确认</Button>
            </Popconfirm>
          ) : (
            <Button onClick={handleSubmit} type="primary">
              确认
            </Button>
          )}
        </div>
      }
    >
      {/* <Modal
      width={800}
      title={title}
      open={createKnowledgeVisible}
      footer={() => (
        <>
          <Button
            onClick={() => {
              formAnalysis.resetFields();
              setCreateKnowledgeVisible(false);
            }}
            type="default"
          >
            取消
          </Button>
          {getCorpusFileTaskBrief?.data?.data?.fileTotal !== 0 &&
          getCorpusFileTaskBrief?.data?.data?.parseUnsuccess !== 0 ? (
            <Popconfirm
              title="确认生成知识库文件?"
              onConfirm={handleSubmit}
              okText="确认"
              cancelText="取消"
            >
              <Button type="primary">确认</Button>
            </Popconfirm>
          ) : (
            <Button onClick={handleSubmit} type="primary">
              确认
            </Button>
          )}
        </>
      )}
      onCancel={() => {
        formAnalysis.resetFields();
        setCreateKnowledgeVisible(false);
      }}
    > */}
      <Form layout="inline" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} form={formAnalysis}>
        <Form.Item hidden name="corpusId" />
        <Form.Item hidden name="ids" />
        <Form.Item hidden name="CorpusFiles" />
        <Col span={12}>
          <Form.Item
            label={'选择知识库'}
            name="knowledgeId"
            rules={[{ required: true, message: '请选择' }]}
          >
            <Select
              style={{ width: '100% ' }}
              placeholder="请选择"
              fieldNames={{ label: 'name', value: 'id' }}
              options={newList}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label={`公开属性`}
            name="openProperty"
            rules={[{ required: true, message: '请选择' }]}
          >
            <Select disabled placeholder="请选择">
              <Select.Option value={OPENENUM.PUBLICP}>无条件公开</Select.Option>
              <Select.Option value={OPENENUM.PROTECTED}>有条件公开</Select.Option>
              <Select.Option value={OPENENUM.PRIVATE}>不予公开</Select.Option>
              <Select.Option value={OPENENUM.DEPT}>部门公开</Select.Option>
            </Select>
          </Form.Item>
        </Col>
        <Col style={{ marginTop: '10.0px' }} span={12}>
          <Form.Item
            label={`敏感等级`}
            name="sensitiveLevel"
            rules={[{ required: true, message: '请选择敏感等级' }]}
          >
            <Select disabled placeholder="请选择">
              <Select.Option value={SENSITIVEENUM.NO_SENSITIVE}>L1不敏感</Select.Option>
              <Select.Option value={SENSITIVEENUM.LOW_SENSITIVE}>L2低敏感</Select.Option>
              <Select.Option value={SENSITIVEENUM.LITTLE_SENSITIVE}>L3较敏感</Select.Option>
              <Select.Option value={SENSITIVEENUM.SENSITIVE}>L4敏感</Select.Option>
            </Select>
          </Form.Item>
        </Col>
      </Form>
      {
        <div>
          <ProTable
            actionRef={actionRef}
            columns={tableColumns}
            // colSize={12}
            form={{
              ignoreRules: false,
              span: 12,
            }}
            rowSelection={{
              defaultSelectedRowKeys: [],
              onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                let arr: Record<string, any>[] = [];
                selectedRows.forEach((item) => {
                  arr.push({ ossUrl: item.ossUrl, fileName: item.fileName });
                });
                formAnalysis.setFieldValue('ids', selectedRowKeys);
                formAnalysis.setFieldValue('CorpusFiles', arr);
              },
            }}
            request={async (
              // 第一个参数 params 查询表单和 params 参数的结合
              // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
              params: any,
            ) => {
              // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
              // 如果需要转化参数可以在这里进行修改
              const msg = await getCorpusFileData({
                ...params,
                corpusBaseId: id,
              });
              console.log(msg);
              return {
                data: msg.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: msg.total,
              };
            }}
            size="middle"
            rowKey="id"
            pagination={{
              showSizeChanger: true,
              defaultPageSize: 10,
            }}
            toolbar={{}}
          />
        </div>
      }
      {/* </Modal> */}
    </Drawer>
  );
};

export default EditAngent;
